from flask import Blueprint, render_template, request, redirect, url_for, g
from .forms import QuestionForm, AnswerForm
from models import QuestionModel, AnswerModel
from exts import db
# 导入自定义装饰器
from decorators import login_required

bp = Blueprint("qa", __name__, url_prefix="/")


@bp.route("/")
def index():
    questions = QuestionModel.query.order_by(QuestionModel.create_time.desc()).all()
    return render_template('index.html', questions=questions)


@bp.route("/public", methods=['GET', 'POST'])
@login_required
def public():
    if request.method == 'POST':
        form = QuestionForm(request.form)
        if form.validate():
            title = form.title.data
            content = form.content.data
            question = QuestionModel(title=title, content=content, author=g.user)
            db.session.add(question)
            db.session.commit()
            return redirect(url_for('qa.index'))
        else:
            print(form.errors)
    else:
        return render_template('public.html')


@bp.route('/detail/<question_id>')
def detail(question_id):
    question = QuestionModel.query.get(question_id)
    return render_template('detail.html', question=question)


@bp.route('/answer/public', methods=["post"])
@login_required
def answer():
    form = AnswerForm(request.form)
    if form.validate():
        content = form.content.data
        # question_id = request.form.get('question_id')
        question_id = form.question_id.data
        answer = AnswerModel(content=content, question_id=question_id, author_id=g.user.id)
        db.session.add(answer)
        db.session.commit()
        return redirect(url_for('qa.detail', question_id=question_id))
    else:
        print(form.errors)
        return redirect(url_for('qa.detail', question_id=request.form.get('question_id')))

@bp.route('/search')
def search():
    q= request.args.get('search')
    questions = QuestionModel.query.filter(QuestionModel.title.contains(q)).all()
    return render_template('index.html', questions=questions)